<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //支付完成 需要有支付时间
        if ($params['pay_type'] == 1 && empty($params['pay_time'])) {
            $this->error('支付完成状态,需要填写支付时间');
        }

        if ($params['status'] == 2 && empty($params['confirm_time'])) {
            $this->error('订单完成状态,需要填写完成时间');
        }

        $orderNoExists = $this->model->field('id')->where('order_no', $params['order_no'])->find();
        if (!empty($orderNoExists)) {
            $this->error('订单号重复,请更换订单号');
        }

        //会员查询
        $member = Db::table('member')->field('nickname,mobile')->where('id', $params['member_id'])->find();
        if (empty($member)) {
            $this->error('用户信息查询失败');
        }

        //产品信息
        $product = Db::table('product')->where('stock', '>', 0)->where('id', $params['product_id'])->find();
        if (empty($product)) {
            $this->error('产品信息查询失败');
        }

        if ($product['stock'] < $params['num']) {
            $this->error('产品库存不足');
        }

        //附加信息存入
        $params['nickname'] = $member['nickname'];
        $params['mobile'] = $member['mobile'];
        $params['price'] = bcmul($product['price'], $params['num'], 2);
        $params['actual_price'] = bcmul($product['price'], $params['num'], 2);

        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            //扣除库存
            Db::table('product')->where('id', $params['product_id'])->setDec('stock', $params['num']);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        //支付完成 需要有支付时间
        if ($params['pay_type'] == 1 && empty($params['pay_time'])) {
            $this->error('支付完成状态,需要填写支付时间');
        }

        if ($params['status'] == 2 && empty($params['confirm_time'])) {
            $this->error('订单完成状态,需要填写完成时间');
        }

        $orderNoExists = $this->model->field('id')->where('id', '<>', $ids)->where('order_no', $params['order_no'])->find();
        if (!empty($orderNoExists)) {
            $this->error('订单号重复,请更换订单号');
        }

        //会员查询
        $member = Db::table('member')->where('id', $params['member_id'])->find();
        if (empty($member)) {
            $this->error('用户信息查询失败');
        }

        //原订单信息
        $order = Db::table('order')->where('id', $ids)->find();
        if ($order['status'] == 2) {
            $this->error('已完成订单无法修改');
        }

        //产品信息
        $product = Db::table('product')->where('id', $params['product_id'])->find();
        if (empty($product)) {
            $this->error('产品信息查询失败');
        }

        //更新了下单数量
        if (($order['num'] != $params['num']) && ($product['stock'] < $params['num'])) {
            $this->error('产品库存不足');
        }

        //产品不一致
        if ($order['product_id'] != $params['product_id']) {
            //增加旧产品库存
            Db::table('product')->where('id', $order['product_id'])->setInc('stock', $params['num']);
        } else {
            //库存数量回滚
            if ($order['num'] > $params['num']) {
                Db::table('product')->where('id', $order['product_id'])->setInc('stock', $order['stock'] - $params['stock']);
            }
        }

        //附加信息存入
        $params['nickname'] = $member['nickname'];
        $params['mobile'] = $member['mobile'];
        $params['price'] = bcmul($product['price'], $params['num'], 2);
        $params['actual_price'] = bcmul($product['price'], $params['num'], 2);

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            //扣除库存
            Db::table('product')->where('id', $params['product_id'])->setDec('stock', $params['num']);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        foreach ($list as $k => $v) {
            if ($v['status'] == 0) { //未完成订单库存回滚
                Db::table('product')->where('id', $v['product_id'])->setInc('stock', $v['num']);
            }
        }

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //插入数组
        $insert = [];
        //扣除库存数组
        $productStock = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];

            $errMsg = ""; //错误信息
            $error = 0; //导入失败行数
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }

                if ($row) {
                    $statusArr = ['进行中' => 0, '已完成' => 2];
                    $payArr = ['待支付' => 0, '已支付' => 1];
                    $row['status'] = !empty($statusArr[$row['status']]) ? $statusArr[$row['status']] : 0;
                    $row['pay_type'] = !empty($payArr[$row['pay_type']]) ? $payArr[$row['pay_type']] : 0;
                    $row['pay_time'] = !empty($row['pay_time']) ? date('Y-m-d H:i:s', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($row['pay_time']) - 8 * 3600) : '';
                    $row['createtime'] = !empty($row['createtime']) ? date('Y-m-d H:i:s', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($row['createtime']) - 8 * 3600) : '';
                    $row['confirm_time'] = !empty($row['confirm_time']) ? date('Y-m-d H:i:s', \PhpOffice\PhpSpreadsheet\Shared\Date::excelToTimestamp($row['confirm_time']) - 8 * 3600) : '';
                    $row['createtime'] = time();

                    $orderNoExists = $this->model->field('id')->where('order_no', $row['order_no'])->find();
                    if (!empty($orderNoExists)) {
                        $errMsg .= '第' . $currentRow . '行订单号重复<br>';
                        $error++;
                        continue;
                    }

                    //产品名称
                    $product = (new \app\admin\model\Product())->field('title,stock')->where('id', $row['product_id'])->find();
                    if (empty($product)) {
                        $errMsg .= '第' . $currentRow . '行商品不存在<br>';
                        $error++;
                        continue;
                    }

                    //预扣除库存
                    $deductionStock = !empty($productStock[$row['product_id']]) ? $productStock[$row['product_id']] : 0;
                    if (($product['stock'] - $deductionStock) < $row['num']) {
                        $errMsg .= '第' . $currentRow . '行产品库存不足<br>';
                        $error++;
                        continue;
                    }

                    $row['product_title'] = $product['title'];

                    //库存写入
                    if (!empty($productStock[$row['product_id']])) {
                        $productStock[$row['product_id']] += $row['num'];
                    } else {
                        $productStock[$row['product_id']] = $row['num'];
                    }

                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }


        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }

            $this->model->saveAll($insert);

            //扣除库存
            $productModel = (new \app\admin\model\Product());
            foreach ($productStock as $k => $v) {
                $productModel->where('id', $k)->setDec('stock', $v);
            }
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        //成功条数
        if ($allRow - 1 > $error) {
            $success = ($allRow - 1 - $error) . "条导入成功<br>";
        }

        $this->success($success . $error . "条数据导入失败<br>原因:<br>" . $errMsg);
    }


    /**
     * @author TechKoga
     * @date 2022/2/16
     * @describe 导出
     */
    public function export()
    {
        if ($this->request->isAjax()) {
            set_time_limit(0);
            ini_set('max_execution_time', 0);
            ini_set('memory_limit', -1);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $header = ['订单号', '产品名称', '数量', '价格', '实际付款', '昵称', '手机号', '详细地址', '支付状态', '支付时间', '订单状态', '完成时间', '下单时间'];
            $filePath = "uploads/csv/导出订单" . date('Y-m-d') . '_' . mt_rand(0, 99);

            //订单总数
            $count = $this->model
                ->field('order_no,member_id,nickname,mobile,address,product_id,num,price,actual_price,pay_type,pay_time,status,confirm_time,createtime')
                ->where($where)
                ->count();

            //单表数据量
            $sqlLimit = 100000;

            //到数量刷新buffer
            $limit = 5000;

            //计数器
            $cnt = 0;

            $statusArr = [0 => '进行中', 2 => '已完成'];
            $payArr = [0 => '待支付', 1 => '已支付'];

            $fileNameArr = array();
            // 逐行取出数据，不浪费内存
            $page = ceil($count / $sqlLimit);
            for ($i = 0; $i < $page; $i++) {
                $fp = fopen($filePath . '_' . $i . '.csv', 'w'); //生成临时文件
                $fileNameArr[] = $filePath . '_' . $i . '.csv';

                //将数据通过fputcsv写到文件句柄
                fputcsv($fp, $header);

                $dataArr = $this->model
                    ->field('order_no,product_title,num,price,actual_price,nickname,mobile,address,pay_type,pay_time,status,confirm_time,createtime')
                    ->where($where)
                    ->limit($i * $sqlLimit, $sqlLimit)
                    ->select();

                foreach ($dataArr as $k => $v) {
                    $v['status'] = !empty($statusArr[$v['status']]) ? $statusArr[$v['status']] : 0;
                    $v['pay_type'] = !empty($payArr[$v['pay_type']]) ? $payArr[$v['pay_type']] : 0;

                    $cnt++;
                    if ($limit == $cnt) {
                        //刷新一下输出buffer，防止由于数据过多造成问题
                        ob_flush();

                        $cnt = 0;
                    }
                    fputcsv($fp, $v->toArray());
                }
                fclose($fp);  //每生成一个文件关闭
            }

            //进行多个文件压缩
            $zip = new \ZipArchive();
            $filename = $filePath . '.zip';
            $zip->open($filename, \ZipArchive::CREATE);   //打开压缩包
            foreach ($fileNameArr as $file) {
                $zip->addFile($file, basename($file));   //向压缩包中添加文件
            }
            $zip->close();  //关闭压缩包
            foreach ($fileNameArr as $file) {
                unlink($file); //删除csv临时文件
            }

            //获取当前域名
            $domain = request()->domain();
            //输出下载地址
            $this->success('导出成功', $domain . "/" . $filename);
        }
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
